<template>
  <div class="brand-management-page">
    <!-- 页面标题区域 -->
    <div class="page-header">
      <h2 class="page-title">品牌管理/增改</h2>
      <el-button type="success" icon="Link" class="bind-btn" @click="handleBind">
        一键绑定
      </el-button>
    </div>

    <!-- 品牌基础信息卡片 -->
    <el-card class="basic-info-card">
      <div class="form-grid">
        <!-- 品牌名称 -->
        <div class="form-group">
          <label class="form-label required">品牌名称</label>
          <el-input v-model="brandInfo.name" placeholder="请输入品牌名称" class="form-control" />
        </div>

        <!-- 品牌LOGO上传 -->
        <div class="form-group">
          <label class="form-label required">品牌LOGO</label>
          <div class="upload-container">
            <el-upload class="logo-upload" action="#" :auto-upload="false" :show-file-list="false"
              :on-change="handleLogoUpload">
              <el-button size="small" type="default">选择文件</el-button>
            </el-upload>
            <span class="upload-status">
              {{ logoFileName || '未选择文件' }}
              <el-icon v-if="logoFileName" class="clear-upload" @click="clearLogo">
                <Delete />
              </el-icon>
            </span>
          </div>
        </div>

        <!-- 品牌编号 -->
        <div class="form-group">
          <label class="form-label">品牌编号</label>
          <el-input v-model="brandInfo.code" placeholder="自动生成" readonly class="form-control" />
        </div>

        <!-- 品牌状态 -->
        <div class="form-group">
          <label class="form-label required">品牌状态</label>
          <el-radio-group v-model="brandInfo.status" class="status-radio">
            <el-radio label="active">启用</el-radio>
            <el-radio label="inactive">禁用</el-radio>
          </el-radio-group>
        </div>
      </div>
    </el-card>

    <!-- 类别与SKU管理区域 -->
    <el-card class="category-sku-card">
      <div class="category-header">
        <h3 class="section-title">品牌类别管理</h3>

        <!-- 类别切换标签容器 -->
        <div class="category-tabs-container">
          <el-radio-group v-model="activeCategory" class="category-tabs" @change="handleCategoryChange">
            <!-- 默认类别 - 不可删除 -->
            <el-radio-button label="single">
              单品
            </el-radio-button>
            <el-radio-button label="set">
              套盒
            </el-radio-button>
            <el-radio-button label="other">
              其他
            </el-radio-button>

            <!-- 自定义类别 - 可删除 -->
            <template v-for="category in customCategories" :key="category">
              <el-radio-button :label="category" class="custom-category">
                <span>{{ category }}</span>
                <el-icon class="delete-category" @click.stop="deleteCustomCategory(category)">
                  <Delete />
                </el-icon>
              </el-radio-button>
            </template>
          </el-radio-group>
        </div>

        <el-button type="primary" size="small" icon="Plus" class="add-category-btn"
          @click="showAddCategoryDialog = true">
          添加自定义类别
        </el-button>
      </div>

      <!-- SKU档位区域 -->
      <div class="sku-section">
        <div class="sku-header">
          <h4 class="sku-title">{{ currentCategoryText }} SKU档位设置</h4>
          <el-button type="success" size="small" icon="Plus" class="add-sku-btn" @click="addSkuItem">
            添加档位
          </el-button>
        </div>

        <!-- SKU列表 -->
        <div class="sku-list" v-if="currentSkuList.length > 0">
          <div class="sku-item" v-for="(item, index) in currentSkuList" :key="index">
            <div class="sku-fields">
              <el-input v-model="item.name" placeholder="请输入档位名称" class="sku-input name-input" />
              <el-input v-model="item.discount" placeholder="请输入折扣" class="sku-input discount-input" type="number"
                min="0.1" max="9.9" step="0.1" />
              <el-input v-model="item.stock" placeholder="库存阈值" class="sku-input stock-input" type="number" min="0" />
            </div>
            <el-button type="danger" size="small" icon="Delete" class="delete-sku-btn" @click="deleteSkuItem(index)" />
          </div>
        </div>

        <!-- 空状态提示 -->
        <div class="sku-empty" v-else>
          <el-empty description="暂无档位数据，点击添加按钮创建" :image-size="80" />
        </div>
      </div>
    </el-card>

    <!-- 品牌列表表格 -->
    <el-card class="brand-table-card">
      <h3 class="section-title">品牌数据列表</h3>
      <el-table :data="brandTableData" border stripe :header-cell-style="tableHeaderStyle" class="brand-table">
        <el-table-column label="序号" type="index" align="center" width="80" />
        <el-table-column label="品牌LOGO" align="center" width="100">
          <template #default="scope">
            <img v-if="scope.row.logo" :src="scope.row.logo" alt="logo" class="table-logo">
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column label="品牌名称" prop="name" align="center" />
        <el-table-column label="单品折扣" align="center">
          <template #default="scope">
            {{ formatDiscount(scope.row.singleDiscount) }}
          </template>
        </el-table-column>
        <el-table-column label="套盒折扣" align="center">
          <template #default="scope">
            {{ formatDiscount(scope.row.setDiscount) }}
          </template>
        </el-table-column>
        <el-table-column label="其他折扣" align="center">
          <template #default="scope">
            {{ formatDiscount(scope.row.otherDiscount) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="200">
          <template #default="scope">
            <el-button type="primary" icon="Edit" @click="editBrand(scope.row)">
              编辑
            </el-button>
            <el-button type="danger" icon="Delete" @click="deleteBrand(scope.row.id)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 操作按钮区域 -->
    <div class="action-buttons">
      <el-button type="primary" class="main-btn" @click="saveBrandInfo">
        保存品牌信息
      </el-button>
      <el-button type="success" class="main-btn" @click="handleContinue">
        继续
      </el-button>
    </div>

    <!-- 添加自定义类别弹窗 -->
    <el-dialog title="添加自定义类别" v-model="showAddCategoryDialog" width="300px">
      <el-input v-model="newCategoryName" placeholder="请输入类别名称" class="category-input" />
      <template #footer>
        <el-button @click="showAddCategoryDialog = false">取消</el-button>
        <el-button type="primary" @click="addCustomCategory">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import { ElMessage, ElMessageBox, ElEmpty } from 'element-plus'
import { Delete, Link, Plus, Edit } from '@element-plus/icons-vue'

// 品牌基础信息
const brandInfo = ref({
  name: '',
  code: '',
  logo: '',
  status: 'active' // active/inactive
})

// LOGO上传状态
const logoFileName = ref('')

// 活跃的类别
const activeCategory = ref('single')

// 自定义类别列表
const customCategories = ref < string[] > ([])

// 弹窗状态
const showAddCategoryDialog = ref(false)
const newCategoryName = ref('')

// SKU数据结构 - 按类别存储
const skuData = ref < Record < string, SkuItem[]>> ({
  single: [],
  set: [],
  other: []
})

// 当前选中类别的SKU列表
const currentSkuList = computed(() => {
  // 如果当前类别不存在，初始化一个空数组
  if (!skuData.value[activeCategory.value]) {
    skuData.value[activeCategory.value] = []
  }
  return skuData.value[activeCategory.value]
})

// 当前类别显示文本
const currentCategoryText = computed(() => {
  const map: Record<string, string> = {
    'single': '单品',
    'set': '套盒',
    'other': '其他'
  }
  // 检查是否为自定义类别
  if (customCategories.value.includes(activeCategory.value)) {
    return activeCategory.value
  }
  return map[activeCategory.value] || '自定义'
})

// 品牌表格数据
const brandTableData = ref([
  {
    id: 1,
    name: '雅诗兰黛',
    logo: 'https://picsum.photos/40/40?random=1',
    singleDiscount: '1.0',
    setDiscount: '0.9',
    otherDiscount: '1.0'
  },
  {
    id: 2,
    name: '兰蔻',
    logo: 'https://picsum.photos/40/40?random=2',
    singleDiscount: '0.95',
    setDiscount: '0.85',
    otherDiscount: '1.0'
  },
  {
    id: 3,
    name: 'SK-II',
    logo: '',
    singleDiscount: '1.0',
    setDiscount: '1.0',
    otherDiscount: '0.9'
  }
])

// 表格头部样式
const tableHeaderStyle = {
  'background-color': '#f5f7fa',
  'font-weight': '500',
  'color': '#4e5969'
}

// 处理LOGO上传
const handleLogoUpload = (file: any) => {
  logoFileName.value = file.name
  // 实际项目中这里会处理文件上传并获取URL
  brandInfo.value.logo = URL.createObjectURL(file.raw)
}

// 清除LOGO
const clearLogo = () => {
  logoFileName.value = ''
  brandInfo.value.logo = ''
}

// 切换类别
const handleCategoryChange = (category: string) => {
  activeCategory.value = category
}

// 添加自定义类别
const addCustomCategory = () => {
  if (!newCategoryName.value.trim()) {
    ElMessage.warning('请输入类别名称')
    return
  }

  const categoryKey = newCategoryName.value.trim()
  // 检查是否与默认类别冲突
  const defaultCategories = ['single', 'set', 'other']
  if (defaultCategories.includes(categoryKey)) {
    ElMessage.warning('该类别名称已被系统占用')
    return
  }

  if (customCategories.value.includes(categoryKey)) {
    ElMessage.warning('该类别已存在')
    return
  }

  // 添加到自定义类别列表
  customCategories.value.push(categoryKey)
  // 初始化该类别的SKU数组
  skuData.value[categoryKey] = []
  // 切换到新类别
  activeCategory.value = categoryKey
  // 重置输入并关闭弹窗
  newCategoryName.value = ''
  showAddCategoryDialog.value = false
  ElMessage.success(`已添加自定义类别：${categoryKey}`)
}

// 删除自定义类别
const deleteCustomCategory = (category: string) => {
  // 如果删除的是当前活跃类别，切换到默认类别
  if (activeCategory.value === category) {
    activeCategory.value = 'single'
  }

  ElMessageBox.confirm(
    `确定要删除类别【${category}】吗？相关SKU数据也会被删除`,
    '删除确认',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    // 从类别列表中移除
    customCategories.value = customCategories.value.filter(item => item !== category)
    // 删除相关SKU数据
    delete skuData.value[category]
    ElMessage.success(`类别【${category}】已删除`)
  })
}

// 添加SKU档位
const addSkuItem = () => {
  const newItem: SkuItem = {
    name: `档位${currentSkuList.value.length + 1}`,
    discount: '1.0',
    stock: '100'
  }
  currentSkuList.value.push(newItem)
}

// 删除SKU档位
const deleteSkuItem = (index: number) => {
  ElMessageBox.confirm(
    `确定要删除【${currentSkuList.value[index].name}】吗？`,
    '删除确认',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    currentSkuList.value.splice(index, 1)
    // 重新编号
    currentSkuList.value.forEach((item, i) => {
      item.name = `档位${i + 1}`
    })
    ElMessage.success('删除成功')
  }).catch(() => {
    // 取消删除
  })
}

// 格式化折扣显示
const formatDiscount = (discount: string) => {
  return discount ? `${Number(discount) * 10}折` : '-'
}

// 一键绑定
const handleBind = () => {
  ElMessage.info('正在执行一键绑定...')
  // 实际项目中添加绑定逻辑
}

// 编辑品牌
const editBrand = (row: any) => {
  brandInfo.value.name = row.name
  brandInfo.value.logo = row.logo
  brandInfo.value.code = `BR-${row.id}`
  ElMessage.info(`正在编辑品牌：${row.name}`)
}

// 删除品牌
const deleteBrand = (id: number) => {
  ElMessageBox.confirm(
    '确定要删除该品牌吗？',
    '删除确认',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'danger'
    }
  ).then(() => {
    brandTableData.value = brandTableData.value.filter(item => item.id !== id)
    ElMessage.success('品牌已删除')
  })
}

// 保存品牌信息
const saveBrandInfo = () => {
  if (!brandInfo.value.name) {
    ElMessage.warning('请输入品牌名称')
    return
  }

  ElMessage.success('品牌信息保存成功')
  // 实际项目中添加保存逻辑
}
const emit = defineEmits(['next']);
// 继续操作
const handleContinue = () => {
  ElMessage.info('继续下一步操作')
  // 实际项目中添加路由跳转逻辑
  emit('next');
}

// SKU数据类型定义
interface SkuItem {
  name: string
  discount: string
  stock: string
}
</script>

<style scoped>
.brand-management-page {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
  font-family: "Microsoft YaHei", sans-serif;
}

/* 页面头部 */
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-title {
  font-size: 18px;
  color: #1d2129;
  font-weight: 600;
  margin: 0;
}

.bind-btn {
  padding: 6px 16px;
  transition: all 0.2s;
}

.bind-btn:hover {
  background-color: #4ca54c;
}

/* 卡片通用样式 */
:deep(.el-card) {
  border-radius: 6px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  border: none;
  margin-bottom: 20px;
  overflow: hidden;
}

:deep(.el-card__body) {
  padding: 16px;
}

/* 基础信息表单 */
.form-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 20px;
}

.form-group {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.form-label {
  font-size: 14px;
  color: #4e5969;
  width: 100px;
  text-align: right;
  margin-right: 12px;
  white-space: nowrap;
}

.required::after {
  content: "*";
  color: #ff4d4f;
  margin-left: 4px;
}

.form-control {
  width: 280px;
}

.upload-container {
  display: flex;
  align-items: center;
  gap: 10px;
}

.upload-status {
  font-size: 13px;
  color: #666;
  display: flex;
  align-items: center;
  gap: 6px;
}

.clear-upload {
  color: #999;
  cursor: pointer;
  font-size: 14px;
  transition: color 0.2s;
}

.clear-upload:hover {
  color: #ff4d4f;
}

.status-radio {
  display: flex;
  gap: 20px;
}

/* 类别与SKU区域 */
.category-header {
  display: flex;
  align-items: center;
  gap: 16px;
  margin-bottom: 20px;
  flex-wrap: wrap;
}

.section-title {
  font-size: 16px;
  color: #1d2129;
  font-weight: 600;
  margin: 0;
  display: flex;
  align-items: center;
  white-space: nowrap;
}

.section-title::before {
  content: "";
  width: 3px;
  height: 16px;
  background-color: #409eff;
  margin-right: 8px;
  border-radius: 2px;
}

.category-tabs-container {
  flex: 1;
  min-width: 300px;
  overflow-x: auto;
  padding-bottom: 5px;
}

.category-tabs {
  display: inline-flex;
  border-bottom: none;
}

:deep(.el-radio-button__inner) {
  border-radius: 4px;
  padding: 6px 18px;
  font-size: 14px;
}

:deep(.el-radio-button:first-child .el-radio-button__inner) {
  border-radius: 4px 0 0 4px;
}

:deep(.el-radio-button:last-child .el-radio-button__inner) {
  border-radius: 0 4px 4px 0;
}

.add-category-btn {
  white-space: nowrap;
}

/* 自定义类别样式 */
.custom-category {
  position: relative;
}

:deep(.custom-category .el-radio-button__inner) {
  padding-right: 30px !important;
}

.delete-category {
  position: absolute;
  right: 5px;
  top: 50%;
  transform: translateY(-50%);
  font-size: 12px;
  color: #999;
  cursor: pointer;
  width: 16px;
  height: 16px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  transition: all 0.2s;
}

.delete-category:hover {
  color: #ff4d4f;
  background-color: rgba(255, 77, 79, 0.1);
}

/* SKU档位区域 */
.sku-section {
  border-top: 1px dashed #e5e6eb;
  padding-top: 16px;
}

.sku-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.sku-title {
  font-size: 14px;
  color: #4e5969;
  font-weight: 500;
  margin: 0;
}

.add-sku-btn {
  transition: all 0.2s;
}

.add-sku-btn:hover {
  background-color: #4ca54c;
}

.sku-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.sku-item {
  display: flex;
  align-items: center;
  gap: 10px;
  padding: 10px;
  background-color: #f9fafc;
  border-radius: 4px;
  transition: background-color 0.2s;
}

.sku-item:hover {
  background-color: #f0f2f5;
}

.sku-fields {
  display: flex;
  gap: 16px;
  flex: 1;
}

.sku-input {
  border-radius: 4px;
}

.name-input {
  width: 180px;
}

.discount-input,
.stock-input {
  width: 120px;
}

.delete-sku-btn {
  width: 36px;
  height: 36px;
  padding: 0;
  opacity: 0.7;
  transition: all 0.2s;
}

.delete-sku-btn:hover {
  opacity: 1;
  background-color: #ff4d4f;
}

.sku-empty {
  padding: 40px 0;
  text-align: center;
}

/* 品牌表格 */
.brand-table-card {
  margin-bottom: 40px;
}

.brand-table {
  margin-top: 10px;
}

.table-logo {
  width: 40px;
  height: 40px;
  border-radius: 4px;
  object-fit: cover;
}

:deep(.el-table__row:hover > td) {
  background-color: #f0f7ff !important;
}

/* 操作按钮 */
.action-buttons {
  display: flex;
  justify-content: center;
  gap: 20px;
  margin-top: 20px;
}

.main-btn {
  padding: 8px 28px;
  font-size: 14px;
  border-radius: 4px;
  transition: all 0.2s;
}

.main-btn:hover {
  transform: translateY(-2px);
}

/* 自定义类别弹窗 */
.category-input {
  width: 100%;
  margin-top: 10px;
}

/* 响应式适配 */
@media (max-width: 1024px) {
  .form-grid {
    grid-template-columns: 1fr;
  }

  .category-header {
    flex-direction: column;
    align-items: flex-start;
  }

  .category-tabs-container {
    width: 100%;
  }
}

@media (max-width: 768px) {
  .form-control {
    width: 100%;
  }

  .sku-fields {
    flex-wrap: wrap;
  }

  .action-buttons {
    flex-direction: column;
    align-items: center;
  }

  .main-btn {
    width: 100%;
  }
}
</style>